<?php
/**
 * | ---------------------------------------------------------------------------------------------------
 * | Author：johnxu <fsyzxz@163.com>.
 * | ---------------------------------------------------------------------------------------------------
 * | Home: https://www.johnxu.net.
 * | ---------------------------------------------------------------------------------------------------
 * | Data: 2019-03-18
 * | ---------------------------------------------------------------------------------------------------
 * | Desc: 咨询用户连接
 * | ---------------------------------------------------------------------------------------------------
 */

namespace app\service\websocket\handler\drivers;

use app\admin\model\Config;
use app\admin\model\Users;
use app\service\websocket\handler\Driver;
use think\Db;

class Init extends Driver
{
    protected function getType()
    {
        return 'connect';
    }


    protected function intercept( \swoole_websocket_server $server, $fd )
    {
        if ( !isset( $this->data['group'] ) || empty( $this->data['group'] ) )
        {
            $server->push( $fd, '{"type": "error", "message": "分配客服失败"}' );

            return false;
        }
        // todo: 对用户进行初始化:分配在线的客服
        $groupInfo = Db::name( 'group' )->where( 'unique_id', $this->data['group'] )->find();
        if ( !$groupInfo )
        {
            $server->push( $fd, '{"type": "error", "message": "当前没有客服在线"}' );

            return false;
        }
        // 判断当前咨询用户是否已经存在，存在更改状态，不存在，插入
        if ( $user = Users::get( [ 'uid' => $this->data['uid'], 'type' => 'guest' ] ) )
        {
            $user->state     = 'online';
            $user->update_at = time();
            $user->fd        = $fd;
        }
        else
        {
            $user            = new Users();
            $user->uid       = $this->data['uid'];
            $user->avatar    = $this->data['avatar'] ?? '/static/admin/img/avatar.png';
            $user->type      = 'guest';
            $user->create_at = time();
            $user->update_at = time();
            $user->fd        = $fd;
            $user->username  = '游客' . $this->data['uid'];

        }
        $user->save();
        // 根据组查询在线客服
        $kefus = Db::view( 'users', '*' )
            ->view( 'users_group', 'group_id', 'users.id=users_group.users_id' )->where( [
                'state'    => 'online',
                'group_id' => $groupInfo['id']
            ] )->select();
        if ( !$kefus )
        {
            $server->push( $fd, '{"type": "error", "message": "当前没有客服在线"}' );

            return false;
        }
        $kefu       = $kefus[array_rand( $kefus )];
        $this->data = [
            'uid'         => $this->data['uid'],
            'kf_uid'      => $kefu['uid'],
            'kf_avatar'   => $kefu['avatar'],
            'kf_nickname' => $kefu['nickname'] ?: $kefu['username'],
            'group'       => $this->data['group'],
            'avatar'      => $user->avatar,
            'nickname'    => $user->nickname
        ];

        // 判断是否开启自动回复
        $reply = Config::getValue( 'reply' )['value'];
        if ( $reply->status == 'normal' )
        {
            swoole_timer_after( 500, function () use ( $server, $fd, $reply ) {
                $server->push( $fd, $this->jsonEncode( [
                    'type' => 'hello',
                    'data' => [
                        'content' => $reply->content,
                        'time'    => time()
                    ]
                ] ) );
            } );
        }

        // 给客服推送消息，有新用户进来
        if ( $server->exist( $kefu['fd'] ) )
        {
            $server->push( $kefu['fd'], $this->jsonEncode( [
                'type' => 'new-user',
                'data' => [
                    'time'     => time(),
                    'uid'      => $this->data['uid'],
                    'avatar'   => $this->data['avatar'],
                    'nickname' => $this->data['nickname']
                ]
            ] ) );
        }

        return true;
    }

    protected function getToInfo()
    {
        return [
            'fd' => $this->getFromInfo()['fd']
        ];
    }
}